<template>
  <!--模糊搜索区域-->
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form :inline="true" :model="searchContract"
                 label-positio="right" label-width="150px" class="demo-form-inline">
          <el-form-item label="合同编号" prop="contractId" >
            <el-input  v-model="searchContract.contractId" placeholder="请输入合同编码"></el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="searchContract.staffName" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <br>
          <el-form-item label="身份证号">
            <el-input v-model="searchContract.cardId" placeholder="请输入身份证号"></el-input>
          </el-form-item>
          <el-form-item label="合同类型">
            <el-select v-model="searchContract.contractType" placeholder="请选择合同类型">
              <el-option label="全部类型合同" value="0"></el-option>
              <el-option label="劳务合同" value="1"></el-option>
              <el-option label="派遣合同" value="2"></el-option>
              <el-option label="临时合同" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="margin-left: 100px">
            <el-button type="primary" @click="search" icon="el-icon-search">搜索</el-button>
            <el-button type="info" @click="resetForm('searchContract')" icon="el-icon-refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域   -->
      <div>
        <template>
          <el-table
            :data="contractList"
            @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column
              type="selection">
            </el-table-column>
            <el-table-column
              type="index"
              label="序号">
              <template slot-scope="scope">
                {{ (pageNum - 1) * pageSize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              prop="contractId"
              label="合同编号"
              width="80">
            </el-table-column>
            <el-table-column
              prop="checkState"
              label="审核状态"
              width="80">
              <template slot-scope="scope">
                <el-tag
                  :type="getCheckStateTagType(scope.row.checkState)"
                  disable-transitions>
                  {{ getCheckStateTagName(scope.row.checkState) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="staffName"
              label="姓名"
              width="80">
            </el-table-column>
            <el-table-column
              prop="cardId"
              label="身份证号"
              width="160">
            </el-table-column>
            <el-table-column
              prop="contractType"
              label="合同类型"
              width="100"
            >
              <template slot-scope="scope">
                <el-tag
                  :type="getContractTypeTagType(scope.row.contractType)"
                  disable-transitions>
                  {{ getContractTypeTagName(scope.row.contractType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              disabled="disabled"
              prop="contractStart"
              label="合同开始时间"
              width="170">
            </el-table-column>
            <el-table-column
              prop="contractEnd"
              label="合同结束时间"
              width="170">
            </el-table-column>
            <el-table-column
              prop="staffCompany"
              label="派遣公司"
              width="100">
            </el-table-column>
            <el-table-column
              prop="createBy"
              label="负责人"
              width="100">
            </el-table-column>
            <el-table-column
              prop="contractState"
              label="合同状态"
              width="80">
              <template slot-scope="scope">
                <el-tag
                  :type="getContractStateTagType(scope.row.contractState)"
                  disable-transitions>
                  {{ getContractStateTagName(scope.row.contractState) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope" >
                <el-button
                  type="success"
                  size="mini"
                  @click="renew(scope.row)">续签</el-button>
                <el-dialog title="合同续签" :visible.sync="dialogFormVisible">
                  <el-form
                    :model="contractInfo"
                    label-position="right"
                    :rules="contractInfoRules"
                    ref="contractInfoRulesForm"
                    label-width="150px"
                    style="max-width: 500px; margin-left: auto; margin-right: auto;"
                  >
                    <!-- 使用 el-row 和 el-col 确保每个表单项占据一行 -->
                    <el-row :gutter="20">
                      <el-col :span="24">
                        <el-form-item label="合同续签开始日期" prop="contractStart">
                          <el-date-picker
                            disabled="disabled"
                            v-model="contractInfo.contractStart"
                            type="datetime"
                            placeholder="选择日期时间"
                            value-format="yyyy-MM-dd HH:mm:ss"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="合同续签结束日期" prop="contractEnd">
                          <el-date-picker
                            v-model="contractInfo.contractEnd"
                            type="datetime"
                            placeholder="选择日期时间"
                            value-format="yyyy-MM-dd HH:mm:ss"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="合同类型" prop="contractType">
                          <el-select v-model="contractInfo.contractType" placeholder="请选择">
                            <el-option label="劳务合同" value="1"></el-option>
                            <el-option label="派遣合同" value="2"></el-option>
                            <el-option label="临时合同" value="3"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="派遣公司" prop="staffCompany">
                          <el-select v-model="contractInfo.staffCompany" placeholder="请选择">
                            <el-option label="公司1" value="公司1"></el-option>
                            <el-option label="公司2" value="公司2"></el-option>
                            <el-option label="公司3" value="公司3"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm('contractInfoRulesForm')">确 定</el-button>
                  </div>
                </el-dialog>
                <el-button
                  size="mini"
                  type="warning"
                  @click="unRenew(scope.row)">不续签</el-button>
              </template>
            </el-table-column>

          </el-table>
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[3,5,7,9]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </template>
      </div>
    </el-card>
  </div>
</template>

<script>
import {contractRenewList, unRenew,renew} from "@/api/contractManage/contractRenew";
export default {
  data() {
    // 自定义校验规则
    const validateEndDate = (rule, value, callback) => {
      if (this.contractInfo.contractStart && this.contractInfo.contractEnd) {
        const start = new Date(this.contractInfo.contractStart);
        const end = new Date(this.contractInfo.contractEnd);

        if (end < start) {
          return callback(new Error('结束日期不能早于开始日期'));
        }
      }
      callback();
    };


    return {
      searchContract: {
        contractId: '', // 合同编号
        staffName: '', // 员工姓名
        cardId: '', // 身份证号
        contractType: '' // 合同类型
      },
      contractList: [],
      ids: [],
      contractStates: [],
      checkState: [],
      total: 0,
      pageNum: 1,
      pageSize: 9,
      contractInfo:{
        contractStart:'',
        contractEnd:'',
        contractType:'',
        staffCompany:'',
        contractId:''
      },
      dialogFormVisible:false,
      contractInfoRules:{
        contractEnd:[
          {required:true,message:'合同续签结束日期不能为空',trigger:'blur'},
          {validator: validateEndDate, trigger: 'blur' }
        ],
        contractType:[
          {required:true,message:'合同类型不能为空',trigger:'blur'}
        ],
        staffCompany:[
          {required:true,message:'派遣公司不能为空',trigger:'blur'}
        ]
      }
    }
  },
  methods: {
    onSubmit() {
      console.log('submit!');
    },
    // 判断审批类型
    getCheckStateTagType(status) {
      const typeMap = {
        '0': 'info',
        '1': 'success',
        '2': 'warning',
        '3': 'primary',
      };
      return typeMap[status] || ''; // 如果状态不在预期范围内，则返回空字符串
    },
    // 审批类型前端展示
    getCheckStateTagName(status) {
      const typeMap = {
        '0': '待审核',
        '1': '已通过',
        '2': '未通过',
        '3': '待提交',
      };
      return typeMap[status] || ''; // 如果状态不在预期范围内，则返回空字符串
    },

    // 判断合同类型
    getContractTypeTagType(status) {
      const typeMap = {
        '1': 'info',
        '2': 'success',
        '3': 'primary'
      };
      return typeMap[status] || ''; // 如果状态不在预期范围内，则返回空字符串
    },
    // 合同类型前端展示
    getContractTypeTagName(status) {
      const typeMap = {
        '1': '劳务合同',
        '2': '派遣合同',
        '3': '临时合同'
      };
      return typeMap[status] || ''; // 如果状态不在预期范围内，则返回空字符串
    },

    // 判断合同状态
    getContractStateTagType(status) {
      const typeMap = {
        '0': '',
        '1': 'success',
        '2': 'warning'
      };
      return typeMap[status] || ''; // 如果状态不在预期范围内，则返回空字符串
    },
    // 合同状态前端展示
    getContractStateTagName(status) {
      const nameMap = {
        '0': '未开始',
        '1': '生效中',
        '2': '已到期'
      };
      return nameMap[status] || '未知'; // 如果状态不在预期范围内，则返回'未知'
    },


    /**
     * 复选框改变
     */
    handleSelectionChange(val){
      const contractStates =[]
      const ids =[]
      const checkState=[]
      for (let i = 0;i<val.length;i++){
        ids.push(val[i].contractId)
        contractStates.push(val[i].contractState)
        checkState.push(val[i].checkState)
      }
      this.checkState = checkState
      this.contractStates = contractStates
      this.ids = ids
    },



    /**
     * 续签
     */
    renew(row){
      this.$confirm("这条合同是否选择续签","提示",{
        confirmButtonText:'确定',
        cancelButtonText:'取消'
      }).then(()=>{
        this.contractInfo = {}
        this.dialogFormVisible = true;
        this.contractInfo.contractStart = row.contractEnd
        this.contractInfo.contractId = row.contractId
      }).catch(()=>{
        this.$message.info("取消续签操作")
      })
    },

    /**
     * 续签对话框
     */
    submitForm(formName){
      this.$refs[formName].validate((valid)=>{
        if (valid){
          renew(this.contractInfo).then(res=>{
            if (res.code === 20000){
              this.$message.success("合同续签成功")
              this.dialogFormVisible = false
              this.pageNum = 1
              this.getContractList()
            }
          })
        }
      })
    },

    /**
     * 不续签,将renew_state置为0
     */
    unRenew(row){
      this.$confirm("这条合同是否选择不续签","提示",{
        confirmButtonText:'确定',
        cancelButtonText:'取消'
      }).then(()=>{
        unRenew({
          contractId:row.contractId
        }).then(res=>{
          if (res.code === 20000){
            this.$message.success("这条合同选择不续签成功")
            this.pageNum = 1
            this.getContractList()
          }
        })
      }).catch(()=>{
        this.$message.info("取消不续签操作")
      })
    },




    /**
     * 查询所有合同
     */
    getContractList(){
      contractRenewList({
        pageNum:this.pageNum,
        pageSize:this.pageSize,
        contractId: this.searchContract.contractId,
        staffName: this.searchContract.staffName,
        cardId: this.searchContract.cardId,
        contractType: this.searchContract.contractType
      }).then(res=>{
        if (res.code === 20000){
          this.contractList = res.data.list
          this.total = res.data.total
        }
      })
    },

    /**
     * 模糊查询
     */
    search(){
      this.getContractList()
    },

    /**
     * 改变当前页
     */
    handleCurrentChange(val){
      this.pageNum = val
      this.getContractList()
    },

    /**
     * 改变每页展示行数
     */
    handleSizeChange(val){
      this.pageSize = val
      this.getContractList()
    },

    /**
     * 重置按钮
     */
    resetForm(formName){
      this.searchContract= {}
    }
  },
  created() {
    this.getContractList()
  },
}
</script>

<style scoped lang="scss">
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  width: auto;
}
.el-input{
  width: 300px;
}
.el-select{
  width: 300px;
}
</style>
